<?php
class UsersController extends AppController{
	public $components = array('Auth', 'Session');
	public $uses = array('User');

	public function beforeFilter(){
		parent::beforeFilter();
		$this -> Auth-> allow('login','logout','index');
	}

	/**
	 * Index
	 */

	public function index(){
		$data = $this->User->find("all");
		$this -> set("data", $data);
	}

	/**
	 * Admin Index
	 */

	public function admin_index(){
		$data = $this->User->find("all");
		$this -> set("data", $data);
	}

	/**
	 * Admin edit user
	 */

	public function admin_edit($id){
		$this-> User -> id = $id;
		if(!$this -> User-> exits()){
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this -> request -> is('post')) {
			if($this-> User-> save($this -> request -> data)){
				$this -> Session -> setFlash('The user has been saved .');
				$this -> redirect(array('action' => 'admin_index'));
			} else{
				$this -> Session -> setFlash('The user could not be saved. Please, try again.');
			}
		} else {
			$this -> request -> data = $this -> User -> read(NULL, $id);
		}
	}

	/**
	 * Admin add user
	 */

	public function admin_add(){
		if($this -> request -> is('post')){
			$this -> User -> create();
			if($this -> User -> save($this -> request -> data)){
				$this -> Session -> setFlash(__('The user has been saved'));
				$this -> redirect(array('action' => 'admin_index'));
			}else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
	}

	/**
	 * Admin delete user
	 */

	public function admin_delete($user_id){
		if(isset($user_id)&&is_numeric($user_id)){
			$data = $this -> User -> read(null, $user_id);
			if(!empty($data)){
				$this -> User -> delete($user_id);
				$this -> Session -> setFlash("Username has been deleted with id=".$user_id);
			} else {
				$this -> Session -> setFlash("Username is not avalible with id=". $user_id);
			}
		} else {
			$this -> Session -> setFlash("Usernam is not avalible with id".$user_id);
		}
		$this -> redirect(array('action' => 'admin_index'));
	}

	/**
	 * Login function	
	 */

	public function login(){
		if($this -> request -> is('post')){
			if($this -> Auth -> login()){
				$this -> redirect($this -> Auth -> redirect());
			} else {
				$this -> Session -> setFlash(__('Invalid username or password, try again'));
			}
		}
	}

	/**
	 * Logout function
	 */

	public function logout(){
		$this -> Session -> Destroy();
		$this -> redirect($this -> Auth -> logout());
	}

}